package com.baishancloud.log.common.util


import cn.hutool.core.util.CharsetUtil

import java.io.InputStream
import java.util.Objects
import scala.collection.mutable.ListBuffer
import scala.util.control.Breaks.{break, breakable}

class FileUtil extends Serializable

/**
 * 对于本地文件的一些操作
 *
 * @author ziqiang.wang 
 * @date 2022/4/12 09:29
 */
object FileUtil extends Serializable {

  /**
   * 按行读取 classPath 下的本地文件
   *
   * @param filePath classPath 下的本地文件，注意需要以 / 开头
   * @return 包含文件每一行内容的 List 集合，如果找不到该文件，则集合为空
   */
  def readLines(filePath: String): ListBuffer[String] = {
    val result: ListBuffer[String] = ListBuffer[String]()
    if (filePath == null) {
      return result
    }
    val inputStream: InputStream = FileUtil.getClass.getResourceAsStream(filePath)
    if (inputStream == null) {
      return result
    }
    val readLength: Int = 8192
    val buffer: Array[Byte] = new Array[Byte](readLength)
    val content: StringBuilder = new StringBuilder()
    // 按照 8K 的批次读取本地文件的内容
    breakable {
      while (true) {
        val length: Int = inputStream.read(buffer)
        if (length == -1) {
          break()
        } else {
          if (length < readLength) {
            val temp: Array[Byte] = new Array[Byte](length)
            for (index <- 0 until length) {
              temp(index) = buffer(index)
            }
            content.append(new String(temp, CharsetUtil.UTF_8))
            break()
          } else {
            content.append(new String(buffer, CharsetUtil.UTF_8))
          }
        }
      }
    }
    // 将文件中的数据，按行存放到 list 列表中
    val line: StringBuilder = new StringBuilder()
    content.toString().foreach((elem: Char) => {
      if (Objects.equals(elem, '\n')) {
        result += line.toString()
        line.clear()
      } else {
        line.append(elem)
      }
    })
    result
  }

}
